package org.dfl.plugin.views.actions;

import java.util.Iterator;

import org.dfl.plugin.DflPlugin;
import org.dfl.plugin.views.ViewsManager;
import org.dfl.plugin.views.debug.HistoriesTreeView;
import org.dfl.plugin.views.debug.TokensTreeView;
import org.dfl.plugin.views.debug.model.TokenTreeElem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * action that provide enabling token objects. 
 * It's used in a TokensTreeView (see mapping in plugin.xml file)
 * @author Piotr Wlodarczyk
 *
 */
public class EnableTokenAction extends ActionDelegate{
	
	private IStructuredSelection selection = StructuredSelection.EMPTY;

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection sel) {
		if(sel instanceof IStructuredSelection)
			selection = (IStructuredSelection) sel;
		else 
			selection = StructuredSelection.EMPTY;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.actions.ActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@SuppressWarnings("unchecked")
	public void run(IAction action) {
		if(selection.isEmpty()) return;
		Iterator iter = selection.iterator();
		while(iter.hasNext()){
			Object selObj = iter.next();
			if(selObj instanceof TokenTreeElem){
				HistoriesTreeView historiesTreeView = HistoriesTreeView .getView();
				TokensTreeView tokensTreeView = TokensTreeView.getView();
				
				// place listeners have to be removed before 
				if(historiesTreeView!=null) historiesTreeView.stopListenPlace();
				if(tokensTreeView!=null) tokensTreeView.stopListenPlace();
				
				TokenTreeElem colElem = (TokenTreeElem) selObj;
				synchronized (DflPlugin.class) {
					colElem.getPlace().setTokenActive(colElem.getToken(), true);
				}

				// restore place listeners
				if(historiesTreeView!=null) historiesTreeView.startListenPlace();
				if(tokensTreeView!=null) tokensTreeView.startListenPlace();

				ViewsManager.refreshViews(colElem);
			}
		}
	}
}
